package com.bookshop.logic;

import java.util.ArrayList;

public class CartBuf {
	private final ArrayList<CartItem> mItems;
	
	public CartBuf() {
		mItems = new ArrayList<CartItem>();
	}
	
	public boolean add(String pId) {
		if (indexOf(pId) == -1 && mItems.size() != LogicConstants.MAX_CART_ITEM) {
			mItems.add(new CartItem(pId, 1));
			return true;
		}
		return false;
	}
	

	private int indexOf(String pId) {
		for (int i = 0; i < mItems.size(); i++) {
			if (mItems.get(i).mId.equals(pId)) {
				return i;
			}
		}
		return -1;
	}
	
	public boolean modifiyCount(String pId, int pCount) {
		int index = indexOf(pId);
		if (index == -1) {
			return false;
		} 
		
		mItems.get(index).mCount = pCount;
		return true;
	}
	
	public boolean remove(String pId) {
		int index = indexOf(pId);
		if (index == -1) {
			return false;
		} 
		mItems.remove(index);
		return true;
	}
	
	public String[] getBookIds() {
		int size = mItems.size();
		String[] ids = new String[size];
		
		for (int i = 0; i < size; i++) {
			CartItem item = mItems.get(i);
			ids[i] = item.mId;
		}
		return ids;
	}

	public int[] getCounts() {
		int size = mItems.size();
		int[] counts = new int[size];
		
		for (int i = 0; i < size; i++) {
			CartItem item = mItems.get(i);
			counts[i] = item.mCount;
		}
		return counts;
	}
	
	public int getCount(String pId) {
		int index = indexOf(pId);
		return mItems.get(index).mCount;
	}
}

class CartItem {
	String mId;
	int mCount;
	
	public CartItem(String pId, int pCount) {
		mId = pId;
		mCount = pCount;
	}
}